import bean.Person;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class TestStreamsFilter {
    public static void main(String[] args) {
//        filterList();
//        filterFindAny();

//        moreCondition();

        List<Person> persons = Arrays.asList(
                new Person("mkyong", 30),
                new Person("jack", 20),
                new Person("lawrence", 40)
        );

        String name = persons.stream()
                //判断不等于null x-> x!=null,可简化Objects::nonNull
                .filter(x -> "jack".equals(x.getName()))
                .map(Person::getName)                        //吧流转化为String
                .findAny()
                .orElse("");

        System.out.println("name : " + name);

        List<String> collect = persons.stream()
                .map(Person::getName)
                .collect(Collectors.toList());

        collect.forEach(System.out::println);

    }


    private static void moreCondition() {
        List<Person> persons = Arrays.asList(
                new Person("mkyong", 30),
                new Person("jack", 20),
                new Person("lawrence", 40)
        );

        Person result1 = persons.stream()
                .filter((p) -> "jack".equals(p.getName()) && 20 == p.getAge())
                .findAny()
                .orElse(null);

        System.out.println("result 1 :" + result1);

        //or like this
        Person result2 = persons.stream()
                .filter(p -> {
            if ("jack".equals(p.getName()) && 20 == p.getAge()) {
                return true;
            }
            return false;
        }).findAny()
                .orElse(null);

        System.out.println("result 2 :" + result2);
    }

    private static void filterFindAny() {
        List<Person> persons = Arrays.asList(
                new Person("mkyong", 30),
                new Person("jack", 20),
                new Person("lawrence", 40)
        );

        Person result1 = persons.stream()                        // 转化为流
                .filter(x -> "jack".equals(x.getName()))        // 只过滤出"jack"
                .findAny()                                      // 如果找到了就返回
                .orElse(null);                                  // 如果找不到就返回null

        System.out.println(result1);

        Person result2 = persons.stream()
                .filter(x -> "ahmook".equals(x.getName()))
                .findAny()
                .orElse(null);

        System.out.println(result2);
    }

    private static void filterList() {
        List<String> lines = Arrays.asList("spring", "node", "mkyong");

        List<String> result = lines.stream()                // 转化为一个流
                .filter(line -> !"mkyong".equals(line))     // 排除 'mkyong'
                .collect(Collectors.toList());              // 吧输出流收集回List中

        result.forEach(System.out::println);
    }
}
